/*
 * @Author: xiehangyun 
 * @Date: 2025-05-16 10:32:52 
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2025-09-16 13:53:57
 */
import { Button, Input, Form } from '@nutui/nutui-react-taro';
import { Image, RichText, Text, View } from '@tarojs/components';
import Taro, { useLoad, useShareAppMessage, useShareTimeline } from '@tarojs/taro';
import { toJS } from 'mobx';
import { observer } from 'mobx-react-lite';
import { useEffect, useState } from 'react';
import utilsApi from 'src/api/utilsApi';
import Api from 'src/api/Api';
import PageLayer from 'src/components/PageLayer/PageLayer';
import smallLogoPNG from "src/static/UTlogo.svg";
import utils from 'src/utils/utils';
import acceptInvitationStore from '../AcceptInvitation/acceptInvitationStore';
import promoteRelationshipsStore from '../PromoteRelationships/promoteRelationshipsStore';
import userInfoStore from '../UserInfo/userInfoStore';
import styles from './myPromotion.module.less';
import myPromotionStore from './myPromotionStore';

// 我的推广
const MyPromotion = observer(() => {


    // 申请进度状态 // 1, 填写头像昵称 2.消费金额 .3授权手机号 4.展示推广码
    const [applicationProgressStatus, setApplicationProgressStatus] = useState(0);

    const [promotion_img, setPromotion_img] = useState("");
    // 表单状态
    const [form] = Form.useForm();

    useEffect(() => {
        // 初始化表单数据
        form.setFieldsValue({
            userName: userInfoStore.userName,
            profilePicture: userInfoStore.profilePicture,
        })
    }, [form]);

    useLoad(() => {
        //开启分享
        Taro.showShareMenu({
            withShareTicket: true,
            showShareItems: ['wechatFriends', 'wechatMoment', 'shareAppMessage', 'shareTimeline']
        });
    });

    // 判断当前步骤
    const calcProgressStatus = async () => {

        await userInfoStore.getCurrentUser();

        // 判断当前推广码的申请进度
        if (!userInfoStore.userName || !userInfoStore.profilePicture) {
            setApplicationProgressStatus(1);
            return;
        }

        await myPromotionStore.createPromotionCode(); // 创建新的推广码

        // 2. 消费金额
        if (
            !myPromotionStore.promotionCode.toLowerCase().endsWith('.png') ||
            myPromotionStore.validPaidAmount < myPromotionStore.requiredAmount
        ) {
            setApplicationProgressStatus(2);
            return;
        }

        console.log("phoneNumber", userInfoStore.phoneNumber);
        // 3. 授权手机号
        if (!userInfoStore.phoneNumber) {
            setApplicationProgressStatus(3);
            return;
        }

        // 邀请码
        const promotionCode = userInfoStore.promotionCode || myPromotionStore.promotionCode || "";
        // 4. 展示推广码
        if (promotionCode.toLowerCase().endsWith('.png')) {
            setApplicationProgressStatus(4);
            return;
        }

    }


    useEffect(() => {
        // 如果带有参数, 那就跳转到接受邀请页
        const { scene, userCode } = Taro.getCurrentInstance().router?.params || {};
        console.log("scene", scene, "userCode", userCode);
        if (scene || userCode) {
            Taro.redirectTo({
                url: `/subPages/AcceptInvitation/AcceptInvitation?userCode=${userCode}`,
            });
            return;
        }

        // 请求推广码图片
        utilsApi.queryPropertyByTitle("promotion_img").then((promotion_img) => {
            setPromotion_img(promotion_img);
        });

        // 如果有推广码,就直接跳转到步骤4
        if (userInfoStore.promotionCode) {
            calcProgressStatus();
            return;
        } else {
            setApplicationProgressStatus(0);
            return;
        }

    }, []);

    useShareAppMessage(() => {
        const parame = {
            title: '优T定制',
            path: `/subPages/AcceptInvitation/AcceptInvitation?userCode=${userInfoStore.userCode}`,
            imageUrl: utils.ossSuffix(promotion_img, 512)
        };
        console.log("useShareAppMessage parame", parame);
        return parame;
    });

    useShareTimeline(() => {
        const isShare = promotionCode.toLowerCase().endsWith('.png') && Boolean(userInfoStore.phoneNumber);
        const parame = {
            title: '优T定制',
            query: isShare ? `userCode=${userInfoStore.userCode}` : "",
            imageUrl: utils.ossSuffix(promotion_img, 512)
        };
        console.log("useShareTimeline parame", parame);
        return parame;
    });

    // useDidShow(() => {
    //     // 页面显示时，重新获取推广码和收益数据
    //     myPromotionStore.queryUserIncomeMap(); // 获取用户收益映射信息
    // });

    // useDidHide(() => {
    //     // 页面隐藏时，清除推广码
    //     myPromotionStore.clearPromotionCode();
    // })

    useEffect(() => {
        promoteRelationshipsStore.getNextRelations(true);
        myPromotionStore.queryUserIncomeMap(); // 获取用户收益映射信息
        return () => {
            myPromotionStore.clearPromotionCode();
        }
    }, []);

    const relationsList = toJS(promoteRelationshipsStore.relationsList);

    // 邀请码
    const promotionCode = userInfoStore.promotionCode || myPromotionStore.promotionCode || "";
    // console.log("promotionCode", promotionCode);
    // console.log("consumerThresholdImg", myPromotionStore.consumerThresholdImg);

    console.log("applicationProgressStatus", applicationProgressStatus);

    return (
        <PageLayer
            showBack
            title="我的推广"
            className={styles.myPromotion}
            hasTabBar={false}
        >

            <View className={styles.content}>

                {/* 推广数据统计 */}
                <View className={styles.statsCard}>
                    <View
                        className={styles.statItem}
                        onClick={() => {
                            if (userInfoStore.phoneNumber && relationsList.length > 0) {
                                Taro.navigateTo({
                                    url: '/subPages/PromoteRelationships/PromoteRelationships',
                                });
                            }
                        }}
                    >
                        <View className={styles.statValue}>{promoteRelationshipsStore.total}</View>
                        <View className={styles.statLabel}>累计推广</View>
                    </View>
                    <View
                        className={styles.statItem}
                        onClick={() => {
                            if (userInfoStore.phoneNumber) {
                                Taro.navigateTo({
                                    url: '/subPages/MyIncome/MyIncome',
                                });
                            }
                        }}
                    >
                        <View className={styles.statValue}>¥{myPromotionStore.incomeMoney}</View>
                        <View className={styles.statLabel}>累计收益</View>
                    </View>
                </View>

                {/* 推广二维码 */}
                {
                    applicationProgressStatus === 0 &&
                    <Button
                        className={styles.shareBtn}
                        type="primary"
                        block
                        onClick={() => {
                            // myPromotionStore.createPromotionCode(); // 创建新的推广码
                            calcProgressStatus(); // 判断当前步骤
                        }}
                    >申请推广码</Button>
                }

                {/* 个人信息表单 */}
                {
                    applicationProgressStatus === 1 &&
                    <View
                        className={styles.formCard}
                    >
                        <View className={styles.sectionTitle}>个人信息设置</View>

                        <Form
                            form={form}
                            labelPosition="right"
                            initialValues={{
                                userName: userInfoStore.userName || '',
                                profilePicture: userInfoStore.profilePicture || '',

                            }}
                            onFinish={(values) => {
                                const { profilePicture, userName } = values;
                                // 判断 profilePicture, userName 不能为空
                                if (!profilePicture) {
                                    Taro.showToast({
                                        title: '请选择头像',
                                        icon: 'none'
                                    });
                                    return;
                                }
                                if (!userName) {
                                    Taro.showToast({
                                        title: '请输入昵称',
                                        icon: 'none'
                                    });
                                    return;
                                }
                                const { phoneNumber, sex, birth, } = userInfoStore;
                                userInfoStore.updateUserInfo({ phoneNumber, sex, birth, profilePicture, userName }).then((res) => {
                                    console.log("res", res);
                                    if (res.code === 200) {
                                        calcProgressStatus(); // 判断当前步骤
                                    }
                                });

                            }}
                            onFinishFailed={(errorInfo) => {
                                // 表单验证失败时的处理
                                console.log('表单验证失败:', errorInfo);
                            }}
                        >
                            {/* 头像选择 */}
                            <Form.Item
                                align="center"
                                label="选择头像"
                                name='profilePicture'
                            >
                                <View className={styles.avatarContainer}>
                                    <Button
                                        openType='chooseAvatar'
                                        className={styles.avatarBtn}
                                        onChooseAvatar={async (e) => {
                                            console.log(e);
                                            //@ts-ignore
                                            const avatarUrl = e.mpEvent.detail.avatarUrl;
                                            console.log("avatarUrl", avatarUrl);
                                            const url = await utilsApi.uploadOss(avatarUrl, Api.ossDirectory);
                                            form.setFieldsValue({ profilePicture: url });
                                            // 同时更新 userInfoStore 中的值，确保头像能够正确更新显示
                                            userInfoStore.profilePicture = url;
                                        }}
                                    >
                                        <Image
                                            className={styles.avatarSmall}
                                            src={form.getFieldValue('profilePicture') ? utils.ossSuffix(form.getFieldValue('profilePicture')) : smallLogoPNG}
                                        />
                                    </Button>
                                </View>
                            </Form.Item>

                            {/* 昵称输入 */}
                            <Form.Item
                                align="center"
                                label="昵称"
                                name="userName"
                            >
                                <Input
                                    type="nickname"
                                    className={styles.formInput}
                                    placeholder="请输入昵称"
                                />
                            </Form.Item>

                            <Button
                                nativeType="submit"
                                className={styles.submitBtn}
                                type="primary"
                                block
                                onClick={() => {
                                    form.submit();
                                }}
                            >下一步</Button>

                        </Form>
                    </View>
                }

                {/* 申请进度条 */}
                {
                    // myPromotionStore.promotionCode && !myPromotionStore.promotionCode.toLowerCase().endsWith('.png') && (
                    applicationProgressStatus === 2 &&
                    <View className={styles.progressCard}>
                        <View className={styles.progressHeader}>
                            <Text className={styles.progressTitle}>申请进度</Text>
                            <Text className={styles.progressPercentage}> {Math.floor(myPromotionStore.validPaidAmount / myPromotionStore.requiredAmount * 100)}%</Text>
                        </View>
                        <View className={styles.progressBarContainer}>
                            <View className={styles.progressBar}>
                                <View className={styles.progressFill} style={{ width: `${Math.floor(myPromotionStore.validPaidAmount / myPromotionStore.requiredAmount * 100)}%` }}></View>
                            </View>
                        </View>
                        <View className={styles.progressDescription}>{myPromotionStore.hasParent ? '有' : '无'}上级用户累计消费（不含退款）</View>
                        <View className={styles.progressAmount}>
                            当前：{myPromotionStore.validPaidAmount}元 / 目标：{myPromotionStore.requiredAmount}元
                        </View>
                        <View className={styles.progressHint}>
                            再努力一下就能解锁推广二维码！
                        </View>
                    </View>
                    // )
                }

                {
                    applicationProgressStatus === 3 &&
                    <Button
                        className={styles.shareBtn}
                        type="primary"
                        block
                        openType="getPhoneNumber"
                        onGetPhoneNumber={async e => {
                            await userInfoStore.getPhoneNumber(e);
                            calcProgressStatus(); // 判断当前步骤
                        }}
                    >
                        授权手机号
                    </Button>
                }

                {
                    // promotionCode.toLowerCase().endsWith('.png') && (
                    applicationProgressStatus === 4 &&
                    <View className={styles.qrCodeSection}>
                        <View className={styles.sectionTitle}>我的推广二维码</View>
                        <View className={styles.qrCodeContainer}>

                            <Image
                                src={utils.ossSuffix(promotionCode)}
                                className={styles.qrCodePlaceholder}
                                show-menu-by-longpress
                            />

                            <Button
                                type='primary'
                                className={styles.downloadBtn}
                                onClick={() => {
                                    // 下载推广码二维码
                                    Taro.showLoading({ title: '下载中...' });
                                    Taro.downloadFile({
                                        url: utils.ossSuffix(promotionCode),
                                        success: (res) => {
                                            if (res.statusCode === 200) {
                                                Taro.saveImageToPhotosAlbum({
                                                    filePath: res.tempFilePath,
                                                    success: () => {
                                                        Taro.hideLoading();
                                                        Taro.showToast({
                                                            title: '下载成功',
                                                            icon: 'success'
                                                        });
                                                    },
                                                    fail: (err) => {
                                                        Taro.hideLoading();
                                                        Taro.showToast({
                                                            title: '下载失败',
                                                            icon: 'none'
                                                        });
                                                        console.error('保存图片失败:', err);
                                                    }
                                                });
                                            }
                                        },
                                        fail: (err) => {
                                            Taro.hideLoading();
                                            Taro.showToast({
                                                title: '下载失败',
                                                icon: 'none'
                                            });
                                            console.error('下载图片失败:', err);
                                        }
                                    });
                                }}
                            >
                                下载推广码
                            </Button>

                            <View className={styles.shareHint}>扫描二维码加入我们</View>

                            <View
                                className={styles.qrCodeText}
                                onClick={() => {
                                    Taro.setClipboardData({
                                        data: userInfoStore.userCode,
                                        success: () => {
                                            Taro.showToast({
                                                title: '邀请码已复制',
                                                icon: 'success'
                                            });
                                        }
                                    });
                                }}
                            >
                                {userInfoStore.userCode}
                                <Button
                                    type="primary"
                                    fill="outline"
                                    size="small"
                                    className={styles.copy}
                                >复制</Button>
                            </View>
                        </View>

                        <Button
                            className={styles.shareBtn}
                            openType="share"
                            type="primary"
                            block
                        > {acceptInvitationStore.popButtonText || "一键邀请"}</Button>
                    </View>
                }

                {/* 推广规则 */}
                <View className={styles.rulesSection}>
                    <View className={styles.sectionTitle}>推广规则</View>
                    <RichText
                        className="ql-editor"
                        nodes={acceptInvitationStore.promotionRole.replace(/<img([^>]*)>/g, '<img style="max-width:100%;height:auto;" $1>')}
                    />
                </View>
            </View>

        </PageLayer >
    );
});

export default MyPromotion;